package com.chushouya.controller.open;

import com.chushouya.common.annotations.AuthSkip;
import com.chushouya.order.dto.api.dangdang.DangDangResponse;
import com.chushouya.order.service.api.DangDangApiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 当当公司API控制器
 * 用于接收DangDang系统的回调通知
 *
 * @author chushouya
 * @date 2025-10-31
 */
@Slf4j
@RestController
@RequestMapping("/api/company")
@Api(tags = "当当公司API接口")
public class DangDangCompanyApiController {

    @Resource
    private DangDangApiService dangDangApiService;

    /**
     * 当当取消订单接口
     * DangDang调用此接口通知订单取消
     */
    @PostMapping("/close_order_info")
    @AuthSkip
    @ApiOperation("当当取消订单通知")
    public DangDangResponse<Void> closeOrderInfo(
            @ApiParam(value = "订单号", required = true) @RequestParam("orderSn") String orderSn,
            @ApiParam(value = "取消原因", required = true) @RequestParam("closeInfo") String closeInfo) {
        try {
            log.info("收到当当取消订单通知: orderSn={}, closeInfo={}", orderSn, closeInfo);
            
            // 调用服务处理订单取消
            DangDangResponse<Void> response = dangDangApiService.cancelOrder(orderSn, closeInfo);
            
            log.info("当当取消订单处理完成: orderSn={}, code={}, msg={}", 
                orderSn, response.getCode(), response.getMsg());
            return response;
        } catch (Exception e) {
            log.error("处理当当取消订单失败: orderSn={}", orderSn, e);
            
            DangDangResponse<Void> errorResponse = new DangDangResponse<>();
            errorResponse.setCode(-1);
            errorResponse.setMsg("系统异常: " + e.getMessage());
            return errorResponse;
        }
    }
}
